package core

import (
	"fmt"
	"strings"

	"gitee.com/minph/fileScript/common"
)

// Code 源代码语句
type Code string

// StandardCode 标准化行代码
type StandardCode []string

// FormattedCode 格式化行代码
type FormattedCode []string

// AnnoTags 行首标记类型
type AnnoTags []string

// SentenceTag 语句前缀
const SentenceTag = "@"

// StartAnno 行首标记
var StartAnno = []string{"FileScript", "FST", "Main"}

// AnnoTagsDefault 行首标记
var AnnoTagsDefault AnnoTags = (func() []string {
	res := make([]string, len(StartAnno))
	for i, tag := range StartAnno {
		res[i] = SentenceTag + tag
	}
	return res
})()

// Include 检查是否包含
func (a AnnoTags) Include(tag string) bool {
	for _, val := range a {
		if val == tag {
			return true
		}
	}

	return false
}

// CompressCode 压缩代码
func CompressCode(rows []string) StandardCode {
	var res StandardCode
	for _, row := range rows {
		row = strings.TrimSpace(row)
		if len(row) == 0 || strings.HasPrefix(row, "//") {
			continue
		}

		res = append(res, row)
	}

	return res
}

// CheckCode 代码检查
func (rows StandardCode) CheckCode() StandardCode {
	checkHeader(rows)
	return rows
}

// checkHeader 检查是否有 @Main{}
func checkHeader(rows []string) {
	if !AnnoTagsDefault.Include(rows[0]) {
		common.PrintError("Error@fileScript/core.CheckMain", "Bad format at line 1: no @Main tag")
		common.Exit()
	}

	if rows[1] != "{" {
		common.PrintError("Error@fileScript/core.CheckMain", "Bad format at line 2: no \"{\" after @Main tag")
		common.Exit()
	}

	if rows[len(rows)-1] != "}" {
		common.PrintError("Error@fileScript/core.CheckMain", fmt.Sprintf("Bad format at line %v: no \"}\" at last line", len(rows)))
		common.Exit()
	}
}
